<?php
/*
* ten.model  模型
*
* ----------------------------------------------
* 零起飞网络 - 专注于企业管理系统开发
* 以质量求生存，以服务谋发展，以信誉创品牌 !
* ----------------------------------------------
* @copyright Copyright (C) 2017-2025 07FLY Network Technology Co,LTD.
* @license For licensing, see LICENSE.html
* @author ：kfrs <goodkfrs@QQ.com> 574249366
* @version ：1.1.0
* @link ：http://www.07fly.xyz
* @Date:2025-03-06 14:34:45
*/
namespace app\ten\model;
/**
 * 模块层
 */
class Database extends TenBase {
    /**
     * 数据库文件执行导入
     * @param array $param ['module_dir'=>'','sqlfile'=>'install.sql']
     * @return array|bool
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/14 0014
     */
    public function importModuleSqlExec($param = [])
    {
        header('Content-Type:application/json; charset=utf-8');

        if (!isset($param['part']) && !isset($param['start'])) {

            $module_table_file = $param['module_dir']  .DS. $param['sqlfile'];
            if (!file_exists($module_table_file)) {
                throw_response_error($module_table_file . '文件不存在,跳过数据导入步骤！');
                exit;
            }
            //参数1为序号，2，文件，3 ，是否压缩
            $list['1'] = array('0' => 1, '1' => $module_table_file, '2' => 1);

            ksort($list);
            // 检测文件正确性
            $last = end($list);
            if (!(count($list) === $last[0])) {
                return [RESULT_ERROR, '备份文件可能已经损坏，请检查！'];
                exit;
            }
            session('backup_list', $list);
            $res = array('msg' => "初始化完成,数据还原中...", 'module_dir' => $param['module_dir'], 'part' => 1, 'start' => 0, 'status' => DATA_NORMAL);

            $this->importModuleSqlExec($res);

        } elseif (is_numeric($param['part']) && is_numeric($param['start'])) {

            $part = $param['part'];
            $start = $param['start'];
            $list = session('backup_list');
            $path = $param['module_dir'];

            $db = new \lqf\Database($list[$part], array(
                'path' => realpath($path) . SYS_DS_PROS,
                'compress' => $list[$part][2],
                'prefix' => SYS_DB_PREFIX,
                'prefix_tpl' => '#@__'
            ));

            $start = $db->import($start);
            if (false === $start) {
                return [RESULT_ERROR, '还原数据出错已经损坏，请检查！'];
                exit;
            } elseif (0 === $start) { //下一卷
                if (isset($list[++$part])) {
                    $res = array('msg' => "正在还原...#{$part}", 'module_dir' => $param['module_dir'], 'part' => $part, 'start' => 0, 'status' => DATA_NORMAL);
                    $this->importModuleSqlExec($res);
                } else {
                    session('backup_list', null);
                    return [RESULT_SUCCESS, '还原数据还原完成！', ''];
                    return true;
                }
            } else {
                $data = array('part' => $part, 'start' => $start[0]);
                if ($start[1]) {
                    $rate = floor(100 * ($start[0] / $start[1]));
                    $res = array('msg' => "正在还原...#{$part} ({$rate}%)", 'module_dir' => $param['module_dir'], 'part' => $part, 'start' => $start[0], 'status' => DATA_NORMAL);
                    $this->importModuleSqlExec($res);
                } else {
                    $data['gz'] = 1;
                    $res = array('msg' => "正在还原...#{$part}", 'module_dir' => $param['module_dir'], 'part' => $part, 'start' => $start[0], 'gz' => 1, 'status' => DATA_NORMAL);
                    $this->importModuleSqlExec($res);
                }
            }
        } else {
            return [RESULT_ERROR, '还原数据出错已经损坏，请检查！'];
        }
    }

    /**
     * 导出模块表=》导出到文件
     * $param[] 为模块信息,name tables
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/14 0014
     */
    public function exportModuleTable($param = [])
    {
        //判断是模块的数据表
        if (empty($param['tables'])) {
            return [RESULT_SUCCESS, '模块数据库表为空'];
            exit;
        } else {
            $param['tables'] = str_replace("\r\n", "", $param['tables']);
            $tableArr = str2arr($param['tables'], ',');
            foreach ($tableArr as $key => $onetable) {
                if (empty($onetable)) continue;
                $tables[] = str_replace(array("\r\n", "\r", "\n"), "", $onetable);
            }
        }
        $module_table_path = $param['module_dir'];
        !is_dir($module_table_path) && mkdir($module_table_path, 0755, true);

        $config = [
            'path' => $module_table_path,
            'part' => '524288000',
            'compress' => '0',
            'level' => '9',
            'prefix' => SYS_DB_PREFIX,
            'prefix_tpl' => '#@__',
        ];
        session('backup_config', $config);

        // 生成备份文件信息
        $file = ['name' => $param['sqlfilename'], 'part' => DATA_NORMAL];//备份文件名称 Table-1.sql

        file_put_contents($module_table_path . $param['sqlfilename'] . '-' . DATA_NORMAL . '.sql', '');//重新备份文件

        session('backup_file', $file);
        session('backup_tables', $tables);
        $database = new \lqf\Database($file, $config);
        if (false == $database) {
            return [RESULT_ERROR, '备份初始化失败！'];
        }

        $tab = array('id' => 0, 'start' => 0);
        header('Content-Type:application/json; charset=utf-8');
        //$rtn=array('tables' => $param['tables'], 'tab' => $tab, 'status' => DATA_NORMAL);
        $input = ['id' => 0, 'start' => 0];
        $this->exportModuleTableStep2($input);
    }

    /**
     * 数据表备份=》步骤2
     */
    public function exportModuleTableStep2($param = [])
    {

        $id = $param['id'];
        $start = $param['start'];
        $tables = session('backup_tables');
        $database = new \lqf\Database(session('backup_file'), session('backup_config'));

        $start = $database->backup($tables[$id], $start);

        header('Content-Type:application/json; charset=utf-8');

        if (false === $start) {
            return [RESULT_ERROR, '备份模块数据库表有错'];
            exit;
        } elseif (0 === $start) {
            if (isset($tables[++$id])) {
                $tab = array('id' => $id, 'start' => 0);
                //exit(json_encode(array('msg' => $tables[$id].'备份完成', 'tab' => $tab, 'status' => DATA_NORMAL)));
                $this->exportModuleTableStep2($tab);
            } else {
                $config = session('backup_config');
                session('backup_tables', null);
                session('backup_file', null);
                session('backup_config', null);
                return [RESULT_SUCCESS, '备份模块数据库表成功'];
                return true;
            }
        } else {

            $tab = array('id' => $id, 'start' => $start[0]);
            $rate = floor(100 * ($start[0] / $start[1]));
            // exit(json_encode(array('msg' => "正在备份...({$rate}%)", 'tab' => $tab, 'status' => DATA_NORMAL)));
            $this->exportModuleTableStep2($tab);
        }
    }
}
?>